import { ref, reactive } from 'vue'
import { defineStore } from 'pinia'
import * as api from '@/api/order'
import { ElMessage } from 'element-plus'

export const useOrderStore = defineStore('order', () => {
  // 订单列表数据
  const orderList = ref([])
  // 加载状态
  const loading = ref(false)
  // 当前选中的订单状态
  const currentStatus = ref('all')
  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 订单状态选项
  const statusOptions = [
    { label: '全部', value: 'all' },
    { label: '待付款', value: 0 },
    { label: '待发货', value: 1 },
    { label: '已发货', value: 2 },
    { label: '已取消', value: 3 }
  ]

  // 获取订单列表
  const fetchOrderList = async () => {
    loading.value = true
    const params = {
      status: currentStatus.value,
      page: pagination.currentPage,
      per_page: pagination.pageSize
    }
    try {
      const res = await api.getOrderList(params)
      orderList.value = res.list || []
      pagination.total = res.paged.total || 0
    } catch (error) {
      console.error('获取订单列表失败:', error)
      ElMessage.error('获取订单列表失败')
    } finally {
      loading.value = false
    }
  }

  // 切换订单状态
  const changeOrderStatus = (status) => {
    currentStatus.value = status
    pagination.currentPage = 1 // 切换状态时重置为第一页
    fetchOrderList()
  }

  // 更新订单状态
  const cancelOrder = async orderBn => api.cancelOrder(orderBn)
    .then(() => {
      ElMessage.success('订单已取消')
      fetchOrderList() // 刷新列表
    }).catch (error => {
      console.error('更新订单状态失败:', error)
      ElMessage.error('更新状态失败')
    })

  // 处理分页变化
  const handlePageChange = (page) => {
    pagination.currentPage = page
    fetchOrderList()
  }

  // 处理每页条数变化
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    fetchOrderList()
  }

  return {
    orderList,
    loading,
    currentStatus,
    pagination,
    statusOptions,
    fetchOrderList,
    changeOrderStatus,
    cancelOrder,
    handlePageChange,
    handleSizeChange,
  }
})
